<template>
    <div class="exercisesContent">
        <!-- 习题 头部 -->
        <div class="header">
            <div class="headerContent">
                <!-- 返回按钮 -->
                <div class="button" v-if="editMode" @click="
                        router.push({ path: '/course/courseContent/' + courseId + '/courseQuestionBank' });">
                    <span class="iconfont icon-likesprograma-shangyibu1"></span>
                    <div class="backText">返回</div>
                </div>
                <div class="title">
                    <!-- 习题 编号 -->
                    <div class="exercisesNumber" v-if="index > 0">{{ index }}、</div>
                    <div class="exercisesNumber" v-else>{{ exercisesContent?.exercisesId }} :</div>
                    <!-- 习题 标题 -->
                    <div class="exercisesTitle" v-if="!edit">{{ exercisesContent?.title }}</div>
                    <div class="inputBox maxInputBox" v-else>
                        <input type="text" v-model="exercisesContent.title" placeholder="请输入题目标题" />
                    </div>
                </div>
                <!-- 操作按钮 -->
                <div class="button" v-if="!edit && editMode" @click="toEditMode()">
                    <span class="iconfont icon-likesprogrambianji"></span>
                    <div class="backText">编辑</div>
                </div>
                <div class="button" v-else-if="edit && editMode" @click="updateExercises()">
                    <span class="iconfont icon-likesprogrambaocun"></span>
                    <div class="backText">保存</div>
                </div>
            </div>
            <div class="headerContent" v-if="editMode || (previewMode && !writeMode)">
                <div class="backTexts">
                    <div class="backTextTitle">难度</div>
                    <div class="backText" v-if="!edit" :class="getTopicDifficulty(exercisesContent?.difficultyText)">{{ exercisesContent?.difficultyText }}</div>
                    <div class="inputBox"  v-else>
                        <div class="selectBox">
                            <!-- 下拉框列表 -->
                            <select class="select" v-model="exercisesContent.difficulty" aria-label="editDifficulty">
                                <option :value="1">简单</option>
                                <option :value="2">中等</option>
                                <option :value="3">困难</option>
                            </select>
                            <span class="iconfont icon-likesprograma-shangyiye1"></span>
                        </div>
                    </div>
                </div>
                <div class="backTexts" v-if="exercisesContent?.chapterInfo?.chapterName || edit">
                    <div class="backTextTitle">章节</div>
                    <div class="backText label" v-if="!edit">{{ exercisesContent?.chapterInfo?.chapterName }}</div>
                    <div class="inputBox"  v-else>
                        <div class="selectBox">
                            <!-- 下拉框列表 -->
                            <select class="select" v-model="exercisesContent.chapterId" aria-label="editChapterId">
                                <option :value="0">不关联章节</option>
                                <option v-for="option in chapterList" :key="option.chapterId" :value="option.chapterId">
                                  第 {{ option.displayOrder }} 章  {{ option.chapterName }}
                                </option>
                            </select>
                            <span class="iconfont icon-likesprograma-shangyiye1"></span>
                        </div>
                    </div>
                </div>
                <div class="backTexts" v-if="exercisesContent?.knowledges && exercisesContent?.knowledges.length > 0 || edit">
                    <div class="backTextTitle">知识点</div>
                    <div class="backText label" v-if="!edit" v-for="knowledge in exercisesContent?.knowledges">
                        {{ knowledge.knowledgeContent }}
                    </div>
                    <div class="inputBox" v-else>
                        <div class="typeBox listBox slectList">
                            <div v-if="exercisesContent?.knowledges.length <= 0">无关联知识点</div>
                            <div class="typeItem"
                            v-for="knowledge in exercisesContent?.knowledges" :key="knowledge.recordId">
                                {{ knowledge.knowledgeContent }}
                            </div>
                        </div>
                    </div>
                    <div class="button" v-if="edit" @click="showSelectKnowledgeDialog">选择知识点</div>
                </div>
            </div>
            <div class="headerContent" v-if="editMode || (previewMode && !writeMode)">
                <div class="backTexts maxBackTexts">
                    <div class="backTextTitle">描述</div>
                    <div class="describe" v-if="!edit" :class="{'noDescribe': exercisesContent?.eleRemark?.length > 0}">
                        {{ exercisesContent?.eleRemark?.length > 0 ? exercisesContent?.eleRemark : '暂无描述' }}
                    </div>
                    <div class="inputBox maxInputBox" v-else>
                        <input type="text" v-model="exercisesContent.eleRemark" placeholder="请输入习题描述" />
                    </div>
                </div>
            </div>
        </div>
        <div class="materialButton">
            <div class="button" v-if="edit && exercisesContent?.questionStem?.length <= 0 && !addMaterial" @click="addMaterial = true;">
                <span class="iconfont icon-likesprogramplus"></span>
                <div class="backText">添加材料</div>
            </div>
            <div class="button delete" v-if="edit && exercisesContent?.questionStem?.length > 0" @click="
                exercisesContent.questionStem = '';
                addMaterial = false;
            ">
                <span class="iconfont icon-likesprogramhuishouzhan"></span>
                <div class="backText">清空材料</div>
            </div>
            <div class="button" v-if="edit" @click="handlePaymentConfirm()">
                <span class="iconfont icon-likesprogramadvisor-zhinengguwen"></span>
                <div class="backText">AI智能填写</div>
            </div>
            <div class="button" v-if="edit" @click="addQuestion">
                <span class="iconfont icon-likesprogramplus"></span>
                <div class="backText">添加问题</div>
            </div>
        </div>
        <div class="content">
            <!-- 习题 材料 -->
            <div class="contentBox material" v-if="exercisesContent?.questionStem?.length > 0 && !edit" v-html="exercisesContent?.questionStem">
            </div>
            <div class="contentBox" v-else-if="edit && (addMaterial || exercisesContent?.questionStem?.length > 0)">
                <EditorComponent class="editor" v-model="exercisesContent.questionStem" placeholder="请输入内容..." titlePlaceholder="请输入标题..." />
            </div>
            <!-- 习题 题目 -->
            <div class="contentBox questions">
                <div class="questionContent" v-for="(question, index) in exercisesContent?.questions">
                    <div class="questionTitle">
                        <div class="questionNum" v-if="exercisesContent?.questions?.length > 1">{{ index + 1 }}、</div>
                        <div class="questionTitleText" v-if="!edit">
                            {{ question.questionTitle }} 
                            {{ (props.exercisesScore > 0) ? ` （${props.exercisesScore * (question.score / 100)} 分）` : '' }}
                        </div>
                        <div class="inputBox maxInputBox" v-else>
                            <input type="text" v-model="question.questionTitle" placeholder="请输入问题" />
                        </div> 
                        <div class="button delete" v-if="edit" @click="removeQuestion(question)">
                            <span class="iconfont icon-likesprogramhuishouzhan"></span>
                            <div class="backText">移除问题</div>
                        </div>
                    </div>
                    <div class="questionContents">
                        <template v-if="editMode || (previewMode && !writeMode)">
                            <div class="questionContentsTitle">题型</div>
                            <div class="questionTypeScoreText" v-if="!edit">{{ question.questionType }}</div>
                            <div class="inputBox" v-else>
                                <div class="selectBox">
                                    <!-- 下拉框列表 -->
                                    <select class="select" v-model="question.questionType" aria-label="editDifficulty" @change="watchQuestionType(question)">
                                        <option value="选择题">选择题</option>
                                        <option value="判断题">判断题</option>
                                        <option value="填空题">填空题</option>
                                        <option value="简答题">简答题</option>
                                    </select>
                                    <span class="iconfont icon-likesprograma-shangyiye1"></span>
                                </div>
                            </div>
                            <div class="questionContentsTitle" v-if="question?.score || edit">分值占比</div>
                            <div class="questionTypeScoreText" v-if="!edit && question?.score">{{ question?.score }}%</div>
                            <div class="inputBox" v-else-if="edit">
                                <!-- 输入框，只能输入数字，最小值0，最大值100 -->
                                <input type="number" v-model="question.score" placeholder="请输入分值" />
                            </div>
                        </template>
                        <div class="button" v-if="edit && (question?.questionType == '选择题' || question?.questionType == '填空题')" @click="addOption(question)">
                            <span class="iconfont icon-likesprogramplus"></span>
                            <div class="backText">添加选项</div>
                        </div>
                    </div>
                    <div class="questionContents" v-if="question?.questionType == '选择题'">
                        <div class="questionContentsOptions" v-if="question?.answerOptions">
                            <div class="option" v-for="(option, index) in deserialize(question.answerOptions).data" :key="index" @click="() => {
                                if(!edit && !editMode && !(previewMode && !writeMode)) selectAnswer(question, option.number, question.checkbox)
                            }">
                                <span class="optionNum" :class="{'select': isAnswerSelected(question, option.number)}">{{ option.number }}</span>
                                <div class="optionText" v-if="!edit">{{ option.content }}</div>
                                <div class="inputBox maxInputBox" v-else>
                                    <input type="text" v-model="option.content" placeholder="请输入选项内容" @input="updateAnswerOptions(question, option, index)" />
                                </div>
                                <div class="button delete" v-if="edit" @click="removeOption(question, index)">
                                    <span class="iconfont icon-likesprogramhuishouzhan"></span>
                                    <div class="backText">移除选项</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="questionContents" v-if="question?.questionType == '判断题' && !editMode && !(previewMode && !writeMode)">
                        <div class="questionContentsOptions" v-if="question?.answerOptions">
                            <div class="option">
                                <span class="optionNum">对</span>
                            </div>
                            <div class="option">
                                <span class="optionNum">错</span>
                            </div>
                        </div>
                    </div>
                    <div class="questionContents" v-if="question?.questionType == '填空题' && !editMode && !(previewMode && !writeMode)">
                        <div class="questionContentsOptions" v-if="question?.answerOptions">
                            <div class="option" v-for="(option, index) in deserialize(question.answerOptions).data" :key="index">
                                <div class="inputBox maxInputBox">
                                    <input type="text" v-model="option.content" placeholder="请输入选项内容" @input="updateAnswerOptions(question, option, index)" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="questionContents" v-if="question?.questionType == '简答题' && !editMode && !(previewMode && !writeMode)">
                        <div class="questionContentsAnalysis">
                            <EditorComponent class="editor" v-model="question.answer" placeholder="请输入内容..." titlePlaceholder="请输入标题..." />
                        </div>
                    </div>
                    <template v-if="editMode || (previewMode && !writeMode)">
                        <div class="questionContents" v-if="question?.questionType == '选择题'">
                            <div class="questionContentsTitle" v-if="question?.answer || edit">答案</div>
                            <div class="questionContentsAnswer" v-if="question?.answer || edit">
                                <div class="option" v-if="!edit && question?.answer" v-for="answer in deserialize(question.answer).answer" :key="answer">
                                    <span class="optionNum select">{{ answer }}</span>
                                </div>
                                <div class="option" v-else-if="edit" v-for="(option, index) in deserialize(question.answerOptions).data" :key="index" @click="selectAnswer(question, option.number, false)">
                                    <span class="optionNum" :class="{'select': isAnswerSelected(question, option.number)}">{{ option.number }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="questionContents" v-if="question?.questionType == '判断题'">
                            <div class="questionContentsTitle" v-if="question?.answer || edit">答案</div>
                            <div class="questionContentsAnswer" v-if="question?.answer || edit">
                                <div class="option" v-if="!edit && question?.answer" v-for="answer in deserialize(question.answer).answer" :key="answer">
                                    <span class="optionNum select">{{ answer }}</span>
                                </div>
                                <div class="option" v-else-if="edit" v-for="option in deserialize(question.answerOptions).data" :key="option.number" @click="selectAnswer(question, option.number, true)">
                                    <span class="optionNum" :class="{'select': isAnswerSelected(question, option.number)}">{{ option.number }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="questionContents" v-if="question?.questionType == '填空题' || question?.questionType == '简答题'">
                            <div class="questionContentsTitle" v-if="question?.answer || edit">答案</div>
                        </div>
                        <div class="questionContents" v-if="question?.questionType == '填空题'">
                            <div class="questionContentsOptions" v-if="question?.answerOptions">
                                <div class="option" v-for="(option, index) in deserialize(question.answerOptions).data" :key="index">
                                    <div class="optionText" v-if="!edit">{{ option.content }}</div>
                                    <div class="inputBox maxInputBox" v-else>
                                        <input type="text" v-model="option.content" placeholder="请输入选项内容" @input="updateAnswerOptions(question, option, index)" />
                                    </div>
                                    <div class="button delete" v-if="edit" @click="removeOption(question, index)">
                                        <span class="iconfont icon-likesprogramhuishouzhan"></span>
                                        <div class="backText">移除选项</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="questionContents" :class="edit? 'analysisEdit' : ''" v-if="question?.questionType == '简答题'">
                            <div class="optionText" v-if="!edit" v-html="question?.answer"></div>
                            <div class="questionContentsAnalysis" v-else>
                                <EditorComponent class="editor" v-model="question.answer" placeholder="请输入内容..." titlePlaceholder="请输入标题..." />
                            </div>
                        </div>
                        <div class="questionContents analysis" :class="edit? 'analysisEdit' : ''">
                            <div class="questionContentsTitle" v-if="question?.analysis || edit">解析</div>
                            <div class="questionContentsAnalysis" v-if="question?.analysis && !edit" v-html="question.analysis"></div>
                            <div class="questionContentsAnalysis" v-if="edit">
                                <EditorComponent class="editor" v-model="question.analysis" placeholder="请输入内容..." titlePlaceholder="请输入标题..." />
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
        <MessageDialog ref="selectKnowledgeDialog">
            <template v-slot:title>
                <span>关联知识点</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <form>
                        <div class="selectLabel">
                            <div class="inputBox noPadding">
                                <span>所有内容：</span>
                                <div class="typeBox listBox maxType allType">
                                    <div class="typeItem" v-for="knowledge in knowledgeList"
                                        :class="{ 'select': isSelectKnowledge(knowledge) }" :key="knowledge.recordId"
                                        @click="selectKnowledge(knowledge)">
                                        {{ knowledge.knowledgeContent }}
                                    </div>
                                </div>
                            </div>
                            <div class="inputBox noPadding">
                                <span>已选择：</span>
                                <div class="typeBox listBox slectList maxType">
                                    <div class="typeItem" v-for="knowledge in preSelectKnowledge"
                                        :key="knowledge.recordId" @click="selectKnowledge(knowledge)">
                                        {{ knowledge.knowledgeContent }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closeSelectKnowledgeDialog">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="confirmSelectKnowledge">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
    </div>
</template>

<script lang="ts">
import EditorComponent from '@/components/EditorComponent.vue'; 
import { courseApi, exercisesApi } from '@/api/course/Course';
import { defineComponent, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElLoading, ElMessage } from 'element-plus';
import { Chapter, Exercises, KnowledgePoint } from '@/types/Course';
import MessageDialog from '@/components/MessageDialog.vue';

export default defineComponent({
    name: 'exercisesContent',
});

const getTopicDifficulty = (difficulty: string) => {
    switch (difficulty) {
        case '简单':
            return 'simple';
        case '中等':
            return 'medium';
        case '困难':
            return 'difficulty';
        default:
            return 'simple';
    }
}

</script>

<script setup lang="ts">
    const edit = ref(false);
    const addMaterial = ref(false);
    const route = useRoute();
    const router = useRouter();
    const courseId = ref(); // 获取 课程Id 参数
    // 章节列表
    const chapterList = ref<Chapter[]>([]);
    // 知识点列表
    const knowledgeList = ref<KnowledgePoint[]>([]);
    // 预选知识点
    const preSelectKnowledge = ref<KnowledgePoint[]>([]);
    // 选择知识点对话框
    const selectKnowledgeDialog = ref();
    const showSelectKnowledgeDialog = async () => {
        preSelectKnowledge.value = exercisesContent.value.knowledges.slice();
        knowledgeList.value = (await courseApi.chapter.knowledge.getKnowledgePoint(courseId.value, null)).data;
        selectKnowledgeDialog.value.ShowModal();
    }
    const closeSelectKnowledgeDialog = () => {
        preSelectKnowledge.value = [];
        selectKnowledgeDialog.value.Close();
    }
    const isSelectKnowledge = (knowledge: KnowledgePoint) => {
        if (preSelectKnowledge.value.find(_knowledge => _knowledge.recordId === knowledge.recordId)) {
            return true;
        }
        return false;
    }
    // 选择知识点
    const selectKnowledge = (knowledge: KnowledgePoint) => {
        if (preSelectKnowledge.value.find(_knowledge => _knowledge.recordId === knowledge.recordId)) {
            // 移除
            preSelectKnowledge.value = preSelectKnowledge.value.filter(_knowledge => _knowledge.recordId !== knowledge.recordId);
            return;
        }
        preSelectKnowledge.value.push(knowledge);
    }
    // 确定选择知识点
    const confirmSelectKnowledge = () => {
        exercisesContent.value.knowledges = preSelectKnowledge.value.slice();
        closeSelectKnowledgeDialog();
    }

    // 定义props
    const props = withDefaults(defineProps<{
        exercisesId: number;
        // 写题模式
        editMode?: boolean;
        // 做题模式
        writeMode?: boolean;
        // 预览模式
        previewMode?: boolean;
        // 题目序号
        index?: number;
        exercisesScore?: number;
    }>(), {
        exercisesId: 0,      // 题目ID
        editMode: false,
        writeMode: true,
        previewMode: false,
        index: 0,
        exercisesScore: 0,
    });

    // 定义一个提交事件
    const emit = defineEmits<{
        (e: 'submit', data: any): void; // 提交事件
        (e: 'prev'): void; // 上一题
    }>();

    // 反序列化
    const deserialize = (data: string) => {
        try {
            console.log('反序列化数据：', data);
            console.log('反序列化数据：', JSON.parse(data).data);
            return JSON.parse(data);
        } catch (error) {
            console.log('反序列化失败：', error);
            return [];
        }
    }

      // 重置题目数据
    const watchQuestionType = (question: any) => {
      switch (question.questionType) {
        case '选择题':
          question.answerOptions = JSON.stringify({
            data: [
              { number: 'A', content: '请输入选项内容' },
              { number: 'B', content: '请输入选项内容' }
            ]
          });
          question.answer = JSON.stringify({
            keyword: true,
            answer: []
          });
          break;
        case '判断题':
          question.answerOptions = JSON.stringify({
            data: [
              { number: '对', content: '对' },
              { number: '错', content: '错' }
            ]
          });
          question.answer = JSON.stringify({
            keyword: true,
            answer: []
          });
          break;
        case '填空题':
          question.answerOptions = JSON.stringify({
            data: [
              { number: '1', content: '请输入答案' }
            ]
          });
          question.answer = JSON.stringify({
            keyword: true,
            answer: ''
          });
          break;
        case '简答题':
          question.answerOptions = '';
          question.answer = JSON.stringify({
            keyword: true,
            answer: ''
          });
          break;
      }
    }

    const exercisesContent = ref<Exercises>({
	    exercisesId: 0,
	    chapterId: 0,
	    courseId: 0,
	    title: "",
	    questionStem: "",
	    exerciseType: "课程",
	    difficulty: 0,
	    difficultyText: "简单",
	    dataType: "string",
	    eleRemark: "",
        questions: [],
        knowledges: []
    });

    // 获取习题信息
    const getExercises = async (exercisesId: number) => {
        if (!exercisesId && exercisesId === 0) return;
        exercisesApi.getExercisesById(exercisesId).then(res => {
            console.log(res);
            exercisesContent.value = res.data;
            // exercisesContent.value.questions = []
            console.log(exercisesContent.value);
        });
    };

    // 切换编辑模式
    const toEditMode = async () => {
        chapterList.value = (await courseApi.chapter.getList(courseId.value)).data;
        if (!exercisesContent.value.chapterId) exercisesContent.value.chapterId = 0;
        edit.value = true;
        addMaterial.value = false;
    };

    // 更新习题信息
    const updateExercises = async () => {
        edit.value = false;
        addMaterial.value = false;
        // 触发提交事件
        await exercisesApi.updateExercises(exercisesContent.value);
        await getExercises(exercisesContent.value.exercisesId);
        await emit('submit', exercisesContent.value);
        
    };

    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    watch(() => ({
        exercisesIdParam: props.exercisesId,
        courseIdParam: route.params.courseId,
    }), ({exercisesIdParam, courseIdParam}) => {
        courseId.value = parseSafeInt(courseIdParam);
        // 获取课程信息
        getExercises(exercisesIdParam);
    }, { immediate: true, deep: true });

    // 添加选项
    const addOption = (question: any) => {
        try {
            const options = deserialize(question.answerOptions);
            const lastOption = options.data[options.data.length - 1];
            const nextNumber = String.fromCharCode(lastOption.number.charCodeAt(0) + 1);

            options.data.push({
                number: nextNumber,
                content: "请输入选项内容"
            });

            question.answerOptions = JSON.stringify(options);
        } catch (error) {
            console.error('添加选项失败：', error);
        }
    }
    // 更新选项内容
    const updateAnswerOptions = (question: any, answerOptions: any, index: number) => {
        try {
            console.log(question.answerOptions);
            const questionAnswerOptions = deserialize(question.answerOptions);
            questionAnswerOptions.data[index] = answerOptions;
            question.answerOptions = JSON.stringify(questionAnswerOptions);
            console.log(questionAnswerOptions);
        } catch (error) {
            console.error('更新选项失败：', error);
        }
    }

    // 检查答案是否被选中
    const isAnswerSelected = (question: any, optionNumber: string, isUser: boolean = true) => {
        try {
            let currentAnswer = deserialize(question.userAnswerText);
            if(!isUser) currentAnswer = deserialize(question.answer);
            if (!currentAnswer || !currentAnswer.answer) return false;
            return currentAnswer.answer.includes(optionNumber);
        } catch (error) {
            console.error('检查答案失败：', error);
            return false;
        }
    }
    // 选择答案
    const selectAnswer = (question: any, answer: string, isOnlyOne: boolean, isUser: boolean = true) => {
        try {
            let currentAnswer = deserialize(question.userAnswerText);
            if(!isUser) currentAnswer = deserialize(question.answer);
            let answers = currentAnswer?.answer || [];
            
            // 如果答案已存在，则移除；否则添加
            const index = answers.indexOf(answer);
            if (index > -1) {
                answers.splice(index, 1);
            } else {
                if  (isOnlyOne) answers = [answer];
                else answers.push(answer);
            }
            
            // 按字母顺序排序
            answers.sort();
            
            if(isUser)
            question.userAnswerText = JSON.stringify({
                keyword: true,
                answer: answers
            });
            else
            question.answer = JSON.stringify({
                keyword: true,
                answer: answers
            });
        } catch (error) {
            console.error('选择答案失败：', error);
        }
    }

    // 添加题目
    const addQuestion = () => {
        const question = {
            recId: 0,
            exercisesId: 0,
            questionTitle: '',
            questionType: '选择题',
            score: null,
            displayOrder: 0,
            answerOptions: '',
            answer: '',
            answerHtml:'',
            // 是否多选
            checkbox: true,
            analysis: '',
            userAnswerHtml: '',
            userAnswerText: ''
        };
        watchQuestionType(question);
        exercisesContent.value.questions.push(question);
    }

      // 移除问题
    const removeQuestion = (question: any) => {
        const index = exercisesContent.value.questions.findIndex(q => q === question);
        if (index > -1) {
            exercisesContent.value.questions.splice(index, 1);
        }
    }

    // 移除选项
    const removeOption = (question: any, optionIndex: number) => {
        try {
            const options = deserialize(question.answerOptions);
            const minOptions = question.questionType === '填空题' ? 1 : 2;
            
            if (options.data.length > minOptions) {
                options.data.splice(optionIndex, 1);
                // 重新编号选项
                options.data = options.data.map((opt: any, idx: number) => ({
                    number: question.questionType === '填空题' ? String(idx + 1) : String.fromCharCode(65 + idx), // 填空题用数字，选择题用字母
                    content: opt.content
                }));
                question.answerOptions = JSON.stringify(options);
            } else {
                ElMessage.warning(question.questionType === '填空题' ? '至少需要保留一个选项' : '至少需要保留两个选项');
            }
        } catch (error) {
            console.error('移除选项失败：', error);
        }
    }
const handlePaymentConfirm = () => {
  const loadingDialog = ElLoading.service({
    lock: true,
    text: '题目生成中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 模拟支付过程
  setTimeout(() => {
    loadingDialog.close();
        exercisesContent.value.questions.push({
            recId: 0,
            exercisesId: 0,
            questionTitle: "哪个 SQL 语句用于删除表中的所有数据，但保留表结构？",
            questionType: "选择题",
            score: null,
            displayOrder: 0,
            answerOptions: "{\"data\":[{\"number\":\"A\", \"content\":\"DROP TABLE\"}, {\"number\":\"B\", \"content\":\"DELETE FROM\"}, {\"number\":\"C\", \"content\":\"TRUNCATE TABLE\"}, {\"number\":\"D\", \"content\":\"REMOVE TABLE\"}]}",
            answer: "{\"keyword\":true, \"answer\": [\"C\"]}",
            answerHtml: "",
            analysis: `TRUNCATE TABLE：快速清空表数据，保留表结构，不可回滚。
              DELETE FROM：逐行删除数据，保留表结构，可回滚（但慢）。
              DROP TABLE：删除表结构和数据（不符合题意）。
              REMOVE TABLE：MySQL 无此语法（错误选项）。`,
            userAnswerHtml: '',
            userAnswerText: ''
        });
  }, 2000);
};
</script>

<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
.exercisesContent {
    width: 100%;
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
}
.header {
    width: 100%;
    gap: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
}
.header .headerContent {
    width: 100%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}
.header .headerContent .title {
    flex: 1;
    padding: 0 10px;
    gap: 5px;
    font-size: 20px;
    font-weight: bold;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

/* 标签 */
.header .headerContent .backTexts {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    max-width: 100%;
    gap: 10px;
    font-size: 16px;
    padding: 0px 10px;
}
.header .headerContent .backTexts.maxBackTexts {
    flex: 1;
}
.header .headerContent .backTexts .backTextTitle {
    flex-shrink: 0;
    
}
.header .headerContent .backTexts .backText {
    border-radius: 25px;
    padding: 2px 10px;
    max-width: 160px;
    font-size: 14px;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: rgba(255, 255, 255, 1);
}
.header .headerContent .backTexts .backText.label {
    background-color: rgba(65, 185, 255, 1);
}
.header .headerContent .backTexts .backText.simple {
    background-color: rgba(8, 191, 145, 1);
}
.header .headerContent .backTexts .backText.medium {
    background-color: rgba(250, 172, 43, 1);
}
.header .headerContent .backTexts .backText.difficulty {
    background-color: rgba(246, 70, 0, 1);
}

/* 描述 */
.header .headerContent .describe {
    flex: 1;
    min-width: 0;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 按钮 */
.button {
    padding: 3px 10px;
    font-size: 14px;
    gap: 5px;
    flex-shrink: 0;
    color: rgba(255, 255, 255, 1);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all .3s;
    background-color: rgba(65, 185, 255, 1);
}
.button:hover {
    background-color: rgba(65, 185, 255, 0.8);
}
.button:active {
    transition: all .1s;
    background-color: rgba(65, 185, 255, 0.7);
}
.button .iconfont {
    font-size: 16px;
}
.button.delete {
    background-color: rgba(255, 0, 0, 1);
}

/* 输入框 */
.inputBox {
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inputBox.maxInputBox {
    flex: 1;
}

/* 输入框 */
.inputBox span {
    min-width: 80px;
}

.inputBox input,
.inputBox textarea {
    width: 100%;
    height: 35px;
    font-size: 16px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
    background-color: rgba(255, 255, 255, .8);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}

.inputBox.noPadding textarea {
    height: 100px;
    resize: none;
    /* 禁止调整大小 */
    padding: 3px 10px;
    line-height: 28px;
}

.inputBox input:focus,
.inputBox textarea:focus {
    border: 2px solid rgba(65, 185, 255, 1);
    background-color: rgba(255, 255, 255, 1);
}

.inputBox input,
.inputBox .typeBox {
    width: 100%;
    font-size: 14px;
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
    overflow-y: auto;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
}

.inputBox .selectBox,
.inputBox input {
    height: 35px;
    border: 2px solid rgba(200, 200, 200, 1);
}

.inputBox .typeBox {
    min-height: 40px;
    max-height: 80px;
    resize: none;
    /* 禁止调整大小 */
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 3px 10px;
    line-height: 28px;
    background-color: rgba(255, 255, 255, .8);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}

.inputBox .typeBox.maxType {
    max-height: 250px;
}

.inputBox .typeBox.slectList {
    max-height: 150px;
}

.inputBox input:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

.inputBox .listBox {
    border: 2px solid rgba(200, 200, 200, 1);
}

/* 列表 */
.inputBox .typeBox .typeItem {
    display: flex;
    justify-content: center;
    align-items: center;
    /* 单行溢出省略 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 150px;
    padding: 0px 10px;
    height: 30px;
    font-size: 14px;
    border-radius: 10px;
    border: 2px solid rgba(200, 200, 200, 1);
}

.inputBox .typeBox.slectList .typeItem {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}

.inputBox .typeBox .typeItem:hover {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}

.inputBox .typeBox .typeItem.select {
    color: rgb(255, 255, 255);
    border: 2px solid rgba(65, 185, 255, 1);
    background: rgba(65, 185, 255, 1);
}

/* 下拉框 */
.inputBox .selectBox {
    width: 100%;
    border-radius: 5px;
    font-size: 16px;
    padding: 0px 0px;
    color: #333;
    outline: none;
    position: relative;
    cursor: pointer;
    display: flex;
    background-color: rgba(255, 255, 255, .8);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
    justify-content: space-between;
    transition: .3s all;
}
.inputBox .selectBox:focus-within {
    border: 2px solid rgba(65, 185, 255, 1);
    background-color: rgba(255, 255, 255, 1);
}
.inputBox .selectBox:focus-within .iconfont {
    color: rgba(65, 185, 255, 1);
}
.inputBox .selectBox .select {
    width: 100%;
    padding: 0px 10px;
    padding-right: 35px;
    border: 0px solid #ccc;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0);
    font-size: 14px;
    position: relative;
    z-index: 1;
    color: #333;
    outline: none;
    cursor: pointer;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}
.inputBox .selectBox .iconfont {
    width: 30px;
    min-width: 0px;
    font-size: 20px;
    position: absolute;
    right: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(-90deg);
    transition: .3s all;
    color: rgba(100, 100, 100, 1);
}

/* 材料操作按钮 */
.materialButton {
    padding: 10px;
    padding-bottom: 0px;
    display: flex;
    gap: 10px;
    justify-content: center;
    align-items: flex-start;
}

/* 题目内容 */
.content {
    width: 100%;
    flex: 1;
    min-height: 0px;
    padding: 10px;
    padding-bottom: 0px;
    display: flex;
    gap: 10px;
    justify-content: center;
    align-items: flex-start;
}
.content .contentBox {
    width: 100%;
    height: 100%;
    max-height: 100%;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, .5);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
.content .contentBox.material,
.content .contentBox.questions {
    padding: 10px;
    overflow: hidden;
    overflow-y: auto;
}
.content .contentBox.questions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    justify-content: flex-start;
    align-items: flex-start;
}
.content .questions .questionContent {
    width: 100%;
    background-color: rgba(255, 255, 255, 0.3);
    box-shadow: 0 0 5px rgba(50, 50, 50, 0.1);
    padding: 10px;
    border-radius: 5px;
}
.content .questions .questionContent .questionTitle {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 5px;
}
.content .questions .questionContent .questionTitle .questionNum {
    flex-shrink: 0;
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.content .questions .questionContent .questionTitle .questionTitleText {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
}
/* 题型或分值 */
.content .questions .questionContents {
    width: 100%;
    padding: 5px 0px;
    gap: 10px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.content .questions .questionContents .questionContentsTitle {
    flex-shrink: 0;
    font-size: 15px;
    font-weight: bold;
    color: rgba(65, 185, 255, 1);
}
.content .questions .questionContents .questionTypeScoreText {
    padding: 2px 10px;
    font-size: 14px;
    border-radius: 10px;
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, 1);
}
/* 选项 */
.content .questions .questionContents .questionContentsOptions {
    width: 100%;
    gap: 10px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
}
.content .questions .questionContents .questionContentsOptions .option {
    width: 100%;
    padding: 0px 10px;
    gap: 10px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.content .questions .questionContents .option .optionNum {
    flex-shrink: 0;
    width: 28px;
    height: 28px;
    border-radius: 20px;
    color: rgba(65, 185, 255, 1);
    /* background-color: rgba(65, 185, 255, 1); */
    border: 2px solid rgba(65, 185, 255, 1);
    font-size: 15px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: .3s all;
}
.content .questions .questionContents .option .optionNum:hover {
    color: rgba(65, 185, 255, 1);
    background-color: rgba(65, 185, 255, .5);
}
.content .questions .questionContents .option .optionNum.select {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, 1);
}
.content .questions .questionContents .questionContentsOptions .option .optionText {
    flex: 1;
    font-size: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
}
.content .questions .questionContents .questionContentsAnswer {
    width: 100%;
    gap: 10px;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
}
/* 解析 */
.content .questions .questionContents.analysis {
    justify-content: flex-start;
    align-items: flex-start;
    overflow: hidden;
    overflow-y: auto;
}
.content .questions .questionContents.analysisEdit {
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    margin: 10px 0px;
    padding: 10px;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, .8);
}
.content .questions .questionContents.analysis .questionContentsTitle {
    font-size: 16px;
}
.content .questions .questionContents.analysis .questionContentsAnalysis {
    width: 100%;
    max-height: 200px;
    overflow: hidden;
    overflow-y: auto;
}
.content .questions .questionContents.analysisEdit .questionContentsAnalysis {
    height: 300px;
    max-height: 300px;
}

/* 编辑课程对话框 */
.dialogContent form {
    width: 600px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}

.dialogContent form .inputBox {
    width: 550px;
    padding: 10px 0px;
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialogContent form .inputBox.noPadding {
    padding: 10px 0px;
    align-items: flex-start;
}

/* 输入框 */
.dialogContent form .inputBox span {
    min-width: 80px;
}

.dialogContent form .inputBox input,
.dialogContent form .inputBox textarea {
    width: 100%;
    height: 35px;
    font-size: 16px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
}

.dialogContent form .inputBox.noPadding textarea {
    height: 100px;
    resize: none;
    /* 禁止调整大小 */
    padding: 3px 10px;
    line-height: 28px;
}

.dialogContent form .inputBox input:focus,
.dialogContent form .inputBox textarea:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

.dialogContent form .inputBox input,
.dialogContent form .inputBox .typeBox {
    width: 100%;
    font-size: 14px;
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
    overflow-y: auto;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
}

.dialogContent form .inputBox .selectBox,
.dialogContent form .inputBox input {
    height: 35px;
    border: 2px solid rgba(200, 200, 200, 1);
}

.dialogContent form .inputBox .typeBox {
    min-height: 40px;
    max-height: 80px;
    resize: none;
    /* 禁止调整大小 */
    padding: 3px 10px;
    line-height: 28px;
}

.dialogContent form .inputBox .typeBox.maxType {
    max-height: 250px;
}

.dialogContent form .inputBox .typeBox.slectList {
    max-height: 150px;
}

.dialogContent form .inputBox input:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

.dialogContent form .inputBox .listBox {
    border: 2px solid rgba(200, 200, 200, 1);
}

/* 列表 */
.dialogContent form .inputBox .typeBox .typeItem {
    display: flex;
    justify-content: center;
    align-items: center;
    /* 单行溢出省略 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100px;
    height: 30px;
    font-size: 14px;
    border-radius: 10px;
    border: 2px solid rgba(200, 200, 200, 1);
}

.dialogContent form .inputBox .typeBox.slectList .typeItem {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}

.dialogContent form .inputBox .typeBox .typeItem:hover {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}

.dialogContent form .inputBox .typeBox .typeItem.select {
    color: rgb(255, 255, 255);
    border: 2px solid rgba(65, 185, 255, 1);
    background: rgba(65, 185, 255, 1);
}

/* 表单按钮 */
.dialogContent form .inputBox .button {
    min-width: 100px;
    height: 35px;
    overflow: hidden;
    border-radius: 5px;
    margin-left: 10px;
    transition: .3s all;
    display: flex;
    justify-content: center;
    align-items: center;
    color: aliceblue;
    background-color: rgba(65, 185, 255, 1);
}

/* 表单按钮 */
.dialogContent form .inputBox .button:hover {
    background-color: rgba(65, 185, 255, 0.8);
}

.dialogContent form .inputBox .button:active {
    transition: .1s all;
    background-color: rgba(65, 185, 255, 1);
}

/* 禁用按钮 */
.dialogContent form .inputBox .button.disable {
    color: aliceblue;
    background-color: rgba(180, 180, 180, 1);
}

.dialogContent form .inputBox .button.disable:hover {
    background-color: rgba(180, 180, 180, 0.8);
}

.dialogContent form .inputBox .button.disable:active {
    transition: .1s all;
    background-color: rgba(180, 180, 180, 1);
}

/* 下拉框 */
.dialogContent form .inputBox .selectBox {
    width: 100%;
    border-radius: 5px;
    font-size: 16px;
    padding: 0px 0px;
    color: #333;
    outline: none;
    position: relative;
    cursor: pointer;
    display: flex;
    background-color: rgba(0, 0, 0, 0);
    justify-content: space-between;
    transition: .3s all;
}
.dialogContent form .inputBox .selectBox:focus-within {
    border: 2px solid rgba(65, 185, 255, 1);
}
.dialogContent form .inputBox .selectBox:focus-within .iconfont {
    color: rgba(65, 185, 255, 1);
}
.dialogContent form .inputBox .selectBox .select {
    width: 100%;
    padding: 0px 10px;
    padding-right: 35px;
    border: 0px solid #ccc;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0);
    font-size: 14px;
    position: relative;
    z-index: 1;
    color: #333;
    outline: none;
    cursor: pointer;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}
.dialogContent form .inputBox .selectBox .iconfont {
    width: 30px;
    min-width: 0px;
    font-size: 20px;
    position: absolute;
    right: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(-90deg);
    transition: .3s all;
    color: rgba(100, 100, 100, 1);
}

/* 对话框底部按钮 */
.dialogFooterButton {
    width: 100%;
    height: 65px;
    position: relative;
    display: flex;
    color: rgba(65, 185, 255, 1);
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: .3s all;
}

.dialogFooterButton:hover {
    background-color: rgba(200, 200, 200, .15);
}

.dialogFooterButton:active {
    transition: .1s all;
    background-color: rgba(220, 220, 220, .1);
}

.dialogFooterButton .line {
    width: 100%;
    border-right: 1px solid rgba(200, 200, 200, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}

.messageBox {
    padding: 10px;
}

.messageBox.success {
    color: rgba(65, 185, 255, 1);
}

.messageBox.failure {
    color: rgba(255, 0, 0, 1);
}
</style>